import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, Select, DatePicker, message, Dropdown, Space, Popconfirm, ConfigProvider } from 'antd';
import { PlusOutlined, MinusCircleOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import locale from 'antd/locale/zh_CN';
import 'dayjs/locale/zh-cn';
import { fetchProjects, createProject, createTask, updateProject, updateTask, fetchTasks, deleteTask, deleteProject } from '../../config/api/project';

dayjs.locale('zh-cn');
const { Option } = Select;

const ProjectPlan = (props) => {
  console.log('ProjectPlan props:', props);
  const { context } = props;

  const [planData, setPlanData] = useState([]);
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [currentProject, setCurrentProject] = useState(null);
  const [loading, setLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [tasks, setTasks] = useState([]);
  const [loadingTasks, setLoadingTasks] = useState(false);
  const [editTaskModalVisible, setEditTaskModalVisible] = useState(false);
  const [currentTask, setCurrentTask] = useState(null);
  const [editProjectModalVisible, setEditProjectModalVisible] = useState(false);
  const [addTaskModalVisible, setAddTaskModalVisible] = useState(false);
  
  const [form] = Form.useForm();
  const [taskForm] = Form.useForm();
  const [projectForm] = Form.useForm();

  // 获取项目列表
  const fetchProjectList = async () => {
    try {
      setLoading(true);
      const projects = await fetchProjects(context);
      // const mockProjects = [
      //   {
      //     Id: 1,
      //     Title: "项目A",
      //     Description: "这是一个关于A的测试项目",
      //     Owner: "用户A",
      //     Deadline: "2023-12-31 00:00:00",
      //     Status: "进行中",
      //     Created: "2023-10-01 00:00:00",
      //     Modified: "2023-10-01 00:00:00",
      //   },
      //   {
      //     Id: 2,
      //     Title: "项目B",
      //     Description: "这是一个关于B的测试项目",
      //     Owner: "用户B",
      //     Deadline: "2024-01-15 00:00:00",
      //     Status: "待完成",
      //     Created: "2023-11-01 00:00:00",
      //     Modified: "2023-11-01 00:00:00",
      //   },
      // ];
      setPlanData(projects);
    } catch (error) {
      console.error('获取项目列表失败:', error);
      message.error('获取项目列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取项目任务列表
  const fetchProjectTasks = async (projectId) => {
    try {
      setLoadingTasks(true);
      const allTasks = await fetchTasks(context);
      // 过滤出当前项目下的任务
      const projectTasks = allTasks.filter(task => Number(task.ProjectId) === Number(projectId));
      setTasks(projectTasks);
    } catch (error) {
      console.error('获取任务列表失败:', error);
      message.error('获取任务列表失败');
    } finally {
      setLoadingTasks(false);
    }
  };

  useEffect(() => {
    fetchProjectList();
  }, []);

  const handleAddOk = async () => {
    try {
      const values = await form.validateFields();
      
      // 验证任务时间
      const tasks = values.tasks || [];
      for (const task of tasks) {
        if (task.startTime.isAfter(task.endTime)) {
          message.error('任务开始时间不能晚于任务结束时间');
          return;
        }
      }

      // 创建项目
      const project = {
        Title: values.project,
        Description: values.description || '',
        Owner: context.pageContext.user.displayName,
        Deadline: values.deadline.format('YYYY-MM-DD'),
        Status: values.status,
        Created: dayjs().format('YYYY-MM-DD'),
        Modified: dayjs().format('YYYY-MM-DD')
      };

      const newProject = await createProject(project, context);

      // 创建多个任务
      const taskPromises = tasks.map(task => {
        const taskData = {
          Title: task.taskName,
          ProjectId: newProject.Id,
          StartTime: task.startTime.format('YYYY-MM-DD'),
          EndTime: task.endTime.format('YYYY-MM-DD'),
          Priority: task.priority,
          Status: task.taskStatus,
          Category: task.category,
          Notes: task.notes || '',
          Created: dayjs().format('YYYY-MM-DD'),
          Modified: dayjs().format('YYYY-MM-DD')
        };
        return createTask(taskData, context);
      });

      await Promise.all(taskPromises);
      
      setAddModalVisible(false);
      form.resetFields();
      message.success('项目和任务创建成功');
      fetchProjectList();
    } catch (error) {
      console.error('创建项目失败:', error);
      message.error('创建项目失败');
    }
  };

  const handleCancel = () => {
    setAddModalVisible(false);
    setDetailModalVisible(false);
    form.resetFields();
  };

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 70,
      render: (_, __, index) => index + 1,
    },
    {
      title: '项目名称',
      dataIndex: 'Title',
      key: 'Title',
    },
    {
      title: '负责人',
      dataIndex: 'Owner',
      key: 'Owner',
    },
    {
      title: '截止时间',
      dataIndex: 'Deadline',
      key: 'Deadline',
      render: (text) => dayjs(text).format('YYYY-MM-DD')
    },
    {
      title: '状态',
      dataIndex: 'Status',
      key: 'Status',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button 
            type="link" 
            style={{ color: '#1890ff', padding: '0' }}
            onClick={() => viewDetails(record)}
          >
            查看详情
          </Button>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEditProject(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个项目吗？"
            description="删除项目将同时删除所有相关任务"
            onConfirm={() => handleDeleteProject(record.Id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const handleTableChange = (pagination) => {
    setCurrentPage(pagination.current);
    setPageSize(pagination.pageSize);
  };

  const addProject = () => {
    setAddModalVisible(true);
    // const today = moment();
    // const tomorrow = moment().add(1, 'days').set({ hour: 0, minute: 0, second: 0 });
    form.setFieldsValue({
    //   project: "测试项目 " + moment().format('MMDDHHmm'),
    //   description: "这是自动生成的测试项目描述",
    //   deadline: tomorrow,
      status: "待完成",
    //   tasks: [
    //     {
    //       taskName: "测试任务 " + moment().format('MMDDHHmm'),
    //       startTime: today,
    //       endTime: tomorrow,
    //       priority: "中",
    //       taskStatus: "未开始",
    //       category: "开发",
    //       notes: "这是自动生成的测试任务备注",
    //     }
    //   ]
    });
    // 强制取消日期选择器文本选中
    setTimeout(() => {
      const datePickers = document.querySelectorAll('#add-project-modal .ant-picker-input input');
      datePickers.forEach(input => {
        if (input) {
          input.blur(); // 失去焦点
          input.focus(); // 重新聚焦
          if (input.setSelectionRange) {
            input.setSelectionRange(0, 0);
          }
        }
      });
      window.getSelection().removeAllRanges(); // 强制取消所有文本选中
    }, 0);
  };

  const viewDetails = (project) => {
    setCurrentProject(project);
    setDetailModalVisible(true);
    fetchProjectTasks(project.Id);
    // 强制取消日期选择器文本选中
    setTimeout(() => {
      const datePickers = document.querySelectorAll('#edit-project-modal .ant-picker-input input');
      datePickers.forEach(input => {
        if (input) {
          input.blur(); // 失去焦点
          input.focus(); // 重新聚焦
          if (input.setSelectionRange) {
            input.setSelectionRange(0, 0);
          }
        }
      });
      window.getSelection().removeAllRanges(); // 强制取消所有文本选中
    }, 0);
  };

  // 更新项目状态
  const handleProjectStatusUpdate = async (projectId, newStatus) => {
    try {
      const project = planData.find(p => p.Id === projectId);
      if (!project) return;

      const updatedProject = {
        ...project,
        Status: newStatus,
        Modified: dayjs().format('YYYY-MM-DD')
      };

      await updateProject(updatedProject, context);
      message.success('项目状态更新成功');
      fetchProjectList();
    } catch (error) {
      console.error('更新项目状态失败:', error);
      message.error('更新项目状态失败');
    }
  };

  // 更新任务状态
  const handleTaskStatusUpdate = async (taskId, newStatus) => {
    try {
      const task = tasks.find(t => t.Id === taskId);
      if (!task) return;

      const updatedTask = {
        ...task,
        Status: newStatus,
        Modified: dayjs().format('YYYY-MM-DD')
      };

      await updateTask(updatedTask, context);
      message.success('任务状态更新成功');
      if (currentProject) {
        fetchProjectTasks(currentProject.Id);
      }
    } catch (error) {
      console.error('更新任务状态失败:', error);
      message.error('更新任务状态失败');
    }
  };

  // 打开编辑任务模态框
  const handleEditTask = (task) => {
    setCurrentTask(task);
    taskForm.setFieldsValue({
      taskName: task.Title,
      startTime: dayjs(task.StartTime),
      endTime: dayjs(task.EndTime),
      priority: task.Priority,
      taskStatus: task.Status,
      category: task.Category,
      notes: task.Notes
    });
    setEditTaskModalVisible(true);
  };

  // 处理任务编辑提交
  const handleEditTaskOk = async () => {
    try {
      const values = await taskForm.validateFields();
      
      // 验证任务时间
      if (values.startTime.isAfter(values.endTime)) {
        message.error('任务开始时间不能晚于任务结束时间');
        return;
      }

      const updatedTask = {
        ...currentTask,
        Title: values.taskName,
        StartTime: values.startTime.format('YYYY-MM-DD'),
        EndTime: values.endTime.format('YYYY-MM-DD'),
        Priority: values.priority,
        Status: values.taskStatus,
        Category: values.category,
        Notes: values.notes || '',
        Modified: dayjs().format('YYYY-MM-DD')
      };

      await updateTask(updatedTask, context);
      message.success('任务更新成功');
      setEditTaskModalVisible(false);
      taskForm.resetFields();
      if (currentProject) {
        fetchProjectTasks(currentProject.Id);
      }
      // 强制取消日期选择器文本选中
      setTimeout(() => {
        const datePickers = document.querySelectorAll('#edit-task-modal .ant-picker-input input');
        datePickers.forEach(input => {
          if (input) {
            input.blur(); // 失去焦点
            input.focus(); // 重新聚焦
            if (input.setSelectionRange) {
              input.setSelectionRange(0, 0);
            }
          }
        });
        window.getSelection().removeAllRanges(); // 强制取消所有文本选中
      }, 0);
    } catch (error) {
      console.error('更新任务失败:', error);
      message.error('更新任务失败');
    }
  };

  // 处理删除任务
  const handleDeleteTask = async (taskId) => {
    try {
      await deleteTask(taskId, context);
      message.success('任务删除成功');
      if (currentProject) {
        fetchProjectTasks(currentProject.Id);
      }
    } catch (error) {
      console.error('删除任务失败:', error);
      message.error('删除任务失败');
    }
  };

  // 处理删除项目
  const handleDeleteProject = async (projectId) => {
    try {
      await deleteProject(projectId, context);
      message.success('项目删除成功');
      fetchProjectList();
      setDetailModalVisible(false);
    } catch (error) {
      console.error('删除项目失败:', error);
      message.error('删除项目失败');
    }
  };

  // 处理编辑项目
  const handleEditProject = (project) => {
    setCurrentProject(project);
    projectForm.setFieldsValue({
      project: project.Title,
      description: project.Description,
      deadline: dayjs(project.Deadline),
      status: project.Status
    });
    setEditProjectModalVisible(true);
  };

  // 处理编辑项目提交
  const handleEditProjectOk = async () => {
    try {
      const values = await projectForm.validateFields();
      
      const updatedProject = {
        ...currentProject,
        Title: values.project,
        Description: values.description || '',
        Deadline: values.deadline.format('YYYY-MM-DD'),
        Status: values.status,
        Modified: dayjs().format('YYYY-MM-DD')
      };

      await updateProject(updatedProject, context);
      message.success('项目更新成功');
      setEditProjectModalVisible(false);
      projectForm.resetFields();
      fetchProjectList();
      if (detailModalVisible) {
        setCurrentProject(updatedProject);
      }
      // 强制取消日期选择器文本选中
      setTimeout(() => {
        const datePickers = document.querySelectorAll('#edit-project-modal .ant-picker-input input');
        datePickers.forEach(input => {
          if (input) {
            input.blur(); // 失去焦点
            input.focus(); // 重新聚焦
            if (input.setSelectionRange) {
              input.setSelectionRange(0, 0);
            }
          }
        });
        window.getSelection().removeAllRanges(); // 强制取消所有文本选中
      }, 0);
    } catch (error) {
      console.error('更新项目失败:', error);
      message.error('更新项目失败');
    }
  };

  // 处理新增任务
  const handleAddTask = () => {
    taskForm.resetFields();
    setAddTaskModalVisible(true);
    // 默认赋值
    // const today = moment();
    // const tomorrow = moment().add(1, 'days').set({ hour: 0, minute: 0, second: 0 });
    // taskForm.setFieldsValue({
    //   taskName: "测试任务 " + moment().format('MMDDHHmm'),
    //   startTime: today,
    //   endTime: tomorrow,
    //   priority: "中",
    //   taskStatus: "未开始",
    //   category: "开发",
    //   notes: "这是自动生成的测试任务备注",
    // });
    // 强制取消日期选择器文本选中
    setTimeout(() => {
      const datePickers = document.querySelectorAll('#add-task-modal .ant-picker-input input');
      datePickers.forEach(input => {
        if (input) {
          input.blur(); // 失去焦点
          input.focus(); // 重新聚焦
          if (input.setSelectionRange) {
            input.setSelectionRange(0, 0);
          }
        }
      });
      window.getSelection().removeAllRanges(); // 强制取消所有文本选中
    }, 0);
  };

  // 处理新增任务提交
  const handleAddTaskOk = async () => {
    try {
      const values = await taskForm.validateFields();
      
      if (values.startTime.isAfter(values.endTime)) {
        message.error('任务开始时间不能晚于任务结束时间');
        return;
      }

      const taskData = {
        Title: values.taskName,
        ProjectId: currentProject.Id,
        StartTime: values.startTime.format('YYYY-MM-DD'),
        EndTime: values.endTime.format('YYYY-MM-DD'),
        Priority: values.priority,
        Status: values.taskStatus,
        Category: values.category,
        Notes: values.notes || '',
        Created: dayjs().format('YYYY-MM-DD'),
        Modified: dayjs().format('YYYY-MM-DD')
      };

      await createTask(taskData, context);
      message.success('任务创建成功');
      setAddTaskModalVisible(false);
      taskForm.resetFields();
      if (currentProject) {
        fetchProjectTasks(currentProject.Id);
      }
      // 强制取消日期选择器文本选中
      setTimeout(() => {
        const datePickers = document.querySelectorAll('#add-task-modal .ant-picker-input input');
        datePickers.forEach(input => {
          if (input) {
            input.blur(); // 失去焦点
            input.focus(); // 重新聚焦
            if (input.setSelectionRange) {
              input.setSelectionRange(0, 0);
            }
          }
        });
        window.getSelection().removeAllRanges(); // 强制取消所有文本选中
      }, 0);
    } catch (error) {
      console.error('创建任务失败:', error);
      message.error('创建任务失败');
    }
  };

  return (
    <div style={{ padding: '20px' }}>
      <h2 style={{ marginBottom: '16px', fontWeight: 'normal' }}>项目计划</h2>
      
      <div style={{ marginBottom: '16px' }}>
        <Button 
          style={{ 
            borderColor: '#1890ff', 
            color: '#1890ff', 
            borderRadius: '4px',
            backgroundColor: 'white'
          }}
          onClick={addProject}
        >
          新增项目
        </Button>
      </div>

      <div style={{ marginTop: '20px', marginBottom: '20px', borderBottom: '1px solid #f0f0f0' }}></div>

      <Table
        columns={columns}
        dataSource={planData}
        loading={loading}
        pagination={{
          current: currentPage,
          pageSize: pageSize,
          total: planData.length,
          showSizeChanger: true,
          showQuickJumper: true,
          position: ['bottomRight'],
        }}
        onChange={handleTableChange}
      />

   
      <Modal
        title="新增项目"
        open={addModalVisible}
        onOk={handleAddOk}
        onCancel={handleCancel}
        okText="确定"
        cancelText="取消"
        width={800}
        id="add-project-modal"
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="project"
            label="项目名称"
            rules={[{ required: true, message: '请输入项目名称' }]}
          >
            <Input placeholder="请输入项目名称" />
          </Form.Item>
          <Form.Item
            name="description"
            label="项目描述"
          >
            <Input.TextArea placeholder="请输入项目描述" />
          </Form.Item>
          <Form.Item
            name="deadline"
            label="项目截止时间"
            rules={[{ required: true, message: '请选择项目截止时间' }]}
          >
            <DatePicker format="YYYY-MM-DD" placeholder="请选择项目截止时间" style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            name="status"
            label="项目状态"
            rules={[{ required: true, message: '请选择项目状态' }]}
          >
            <Select placeholder="请选择项目状态">
              <Option value="待完成">待完成</Option>
              <Option value="进行中">进行中</Option>
              <Option value="已完成">已完成</Option>
            </Select>
          </Form.Item>

          <div style={{ marginTop: '20px', borderTop: '1px solid #f0f0f0', paddingTop: '20px' }}>
            <h3>任务信息</h3>
            <Form.List name="tasks">
              {(fields, { add, remove }) => (
                <>
                  {fields.map(({ key, name, ...restField }) => (
                    <Space key={key} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
                      <Form.Item
                        {...restField}
                        name={[name, 'taskName']}
                        rules={[{ required: true, message: '请输入任务名称' }]}
                      >
                        <Input placeholder="任务名称" />
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        name={[name, 'startTime']}
                        rules={[{ required: true, message: '请选择开始时间' }]}
                      >
                        <DatePicker format="YYYY-MM-DD" placeholder="开始时间" />
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        name={[name, 'endTime']}
                        rules={[{ required: true, message: '请选择结束时间' }]}
                      >
                        <DatePicker format="YYYY-MM-DD" placeholder="结束时间" />
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        name={[name, 'priority']}
                        rules={[{ required: true, message: '请选择优先级' }]}
                      >
                        <Select placeholder="优先级" style={{ width: 100 }}>
                          <Option value="高">高</Option>
                          <Option value="中">中</Option>
                          <Option value="低">低</Option>
                        </Select>
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        name={[name, 'taskStatus']}
                        rules={[{ required: true, message: '请选择任务状态' }]}
                      >
                        <Select placeholder="任务状态" style={{ width: 100 }}>
                          <Option value="未开始">未开始</Option>
                          <Option value="进行中">进行中</Option>
                          <Option value="已完成">已完成</Option>
                        </Select>
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        name={[name, 'category']}
                        rules={[{ required: true, message: '请选择分类标签' }]}
                      >
                        <Select placeholder="分类标签" style={{ width: 100 }}>
                          <Option value="开发">开发</Option>
                          <Option value="设计">设计</Option>
                          <Option value="测试">测试</Option>
                          <Option value="文档">文档</Option>
                        </Select>
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        name={[name, 'notes']}
                      >
                        <Input placeholder="备注信息" />
                      </Form.Item>
                      <MinusCircleOutlined onClick={() => remove(name)} />
                    </Space>
                  ))}
                  <Form.Item>
                    <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                      添加任务
                    </Button>
                  </Form.Item>
                </>
              )}
            </Form.List>
          </div>
        </Form>
      </Modal>

      <Modal
        title="项目详情"
        open={detailModalVisible}
        onCancel={handleCancel}
        footer={[
          <Button key="close" onClick={handleCancel}>
            关闭
          </Button>
        ]}
        width={1500}
      >
        {currentProject && (
          <div>
            <div style={{ marginBottom: '20px' }}>
              <h3>项目信息</h3>
              <p><strong>项目名称:</strong> {currentProject.Title}</p>
              <p>
                <strong>状态:</strong>{' '}
                <Dropdown
                  menu={{
                    items: [
                      { key: '待完成', label: '待完成' },
                      { key: '进行中', label: '进行中' },
                      { key: '已完成', label: '已完成' }
                    ],
                    onClick: ({ key }) => handleProjectStatusUpdate(currentProject.Id, key)
                  }}
                  trigger={['hover']}
                >
                  <span style={{ 
                    cursor: 'pointer', 
                    color: '#1890ff',
                    padding: '4px 8px',
                    border: '1px solid #d9d9d9',
                    borderRadius: '4px'
                  }}>
                    {currentProject.Status}
                  </span>
                </Dropdown>
              </p>
              <p><strong>负责人:</strong> {currentProject.Owner}</p>
              <p><strong>截止时间:</strong> {dayjs(currentProject.Deadline).format('YYYY-MM-DD')}</p>
              <p><strong>描述:</strong> {currentProject.Description}</p>
            </div>

            <div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
                <h3 style={{ margin: 0 }}>任务列表</h3>
                <Button 
                  type="primary"
                  onClick={handleAddTask}
                  icon={<PlusOutlined />}
                >
                  新增任务
                </Button>
              </div>
              <Table
                dataSource={tasks}
                loading={loadingTasks}
                pagination={false}
                rowKey="Id"
                columns={[
                  {
                    title: '序号',
                    dataIndex: 'index',
                    key: 'index',
                    width: 80,
                    fixed: 'left',
                    render: (_, __, index) => index + 1,
                  },
                  {
                    title: '任务名称',
                    dataIndex: 'Title',
                    key: 'Title',
                    width: 200,
                    fixed: 'left',
                  },
                  {
                    title: '开始时间',
                    dataIndex: 'StartTime',
                    key: 'StartTime',
                    width: 120,
                    render: (text) => dayjs(text).format('YYYY-MM-DD')
                  },
                  {
                    title: '结束时间',
                    dataIndex: 'EndTime',
                    key: 'EndTime',
                    width: 120,
                    render: (text) => dayjs(text).format('YYYY-MM-DD')
                  },
                  {
                    title: '优先级',
                    dataIndex: 'Priority',
                    key: 'Priority',
                    width: 100,
                  },
                  {
                    title: '状态',
                    dataIndex: 'Status',
                    key: 'Status',
                    width: 120,
                    render: (text, record) => (
                      <Dropdown
                        menu={{
                          items: [
                            { key: '未开始', label: '未开始' },
                            { key: '进行中', label: '进行中' },
                            { key: '已完成', label: '已完成' }
                          ],
                          onClick: ({ key }) => handleTaskStatusUpdate(record.Id, key)
                        }}
                        trigger={['hover']}
                      >
                        <span style={{ 
                          cursor: 'pointer', 
                          color: '#1890ff',
                          padding: '4px 8px',
                          border: '1px solid #d9d9d9',
                          borderRadius: '4px'
                        }}>
                          {text}
                        </span>
                      </Dropdown>
                    )
                  },
                  {
                    title: '分类',
                    dataIndex: 'Category',
                    key: 'Category',
                    width: 100,
                  },
                  {
                    title: '备注',
                    dataIndex: 'Notes',
                    key: 'Notes',
                    width: 200,
                  },
                  {
                    title: '创建时间',
                    dataIndex: 'Created',
                    key: 'Created',
                    render: (text) => dayjs(text).format('YYYY-MM-DD')
                  },
                  {
                    title: '修改时间',
                    dataIndex: 'Modified',
                    key: 'Modified',
                    width: 160,
                    render: (text) => dayjs(text).format('YYYY-MM-DD')
                  },
                  {
                    title: '操作',
                    key: 'action',
                    width: 150,
                    fixed: 'right',
                    render: (_, record) => (
                      <Space>
                        <Button
                          type="link"
                          icon={<EditOutlined />}
                          onClick={() => handleEditTask(record)}
                        >
                          编辑
                        </Button>
                        <Popconfirm
                          title="确定要删除这个任务吗？"
                          onConfirm={() => handleDeleteTask(record.Id)}
                          okText="确定"
                          cancelText="取消"
                        >
                          <Button
                            type="link"
                            danger
                            icon={<DeleteOutlined />}
                          >
                            删除
                          </Button>
                        </Popconfirm>
                      </Space>
                    ),
                  }
                ]}
                scroll={{ x: 1600 }}
              />
            </div>
          </div>
        )}
      </Modal>

      {/* 编辑任务模态框 */}
      <Modal
        title="编辑任务"
        open={editTaskModalVisible}
        onOk={handleEditTaskOk}
        onCancel={() => {
          setEditTaskModalVisible(false);
          taskForm.resetFields();
        }}
        okText="确定"
        cancelText="取消"
        id="edit-task-modal"
      >
        <Form
          form={taskForm}
          layout="vertical"
        >
          <Form.Item
            name="taskName"
            label="任务名称"
            rules={[{ required: true, message: '请输入任务名称' }]}
          >
            <Input placeholder="请输入任务名称" />
          </Form.Item>
          <Form.Item
            name="startTime"
            label="开始时间"
            rules={[{ required: true, message: '请选择开始时间' }]}
          >
            <DatePicker format="YYYY-MM-DD" placeholder="请选择开始时间" style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            name="endTime"
            label="结束时间"
            rules={[{ required: true, message: '请选择结束时间' }]}
          >
            <DatePicker format="YYYY-MM-DD" placeholder="请选择结束时间" style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            name="priority"
            label="优先级"
            rules={[{ required: true, message: '请选择优先级' }]}
          >
            <Select placeholder="请选择优先级">
              <Option value="高">高</Option>
              <Option value="中">中</Option>
              <Option value="低">低</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="taskStatus"
            label="任务状态"
            rules={[{ required: true, message: '请选择任务状态' }]}
          >
            <Select placeholder="请选择任务状态">
              <Option value="未开始">未开始</Option>
              <Option value="进行中">进行中</Option>
              <Option value="已完成">已完成</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="category"
            label="分类标签"
            rules={[{ required: true, message: '请选择分类标签' }]}
          >
            <Select placeholder="请选择分类标签">
              <Option value="开发">开发</Option>
              <Option value="设计">设计</Option>
              <Option value="测试">测试</Option>
              <Option value="文档">文档</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="notes"
            label="备注信息"
          >
            <Input.TextArea placeholder="请输入备注信息" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑项目模态框 */}
      <Modal
        title="编辑项目"
        open={editProjectModalVisible}
        onOk={handleEditProjectOk}
        onCancel={() => {
          setEditProjectModalVisible(false);
          projectForm.resetFields();
        }}
        okText="确定"
        cancelText="取消"
        id="edit-project-modal"
      >
        <Form
          form={projectForm}
          layout="vertical"
        >
          <Form.Item
            name="project"
            label="项目名称"
            rules={[{ required: true, message: '请输入项目名称' }]}
          >
            <Input placeholder="请输入项目名称" />
          </Form.Item>
          <Form.Item
            name="description"
            label="项目描述"
          >
            <Input.TextArea placeholder="请输入项目描述" />
          </Form.Item>
          <Form.Item
            name="deadline"
            label="项目截止时间"
            rules={[{ required: true, message: '请选择项目截止时间' }]}
          >
            <DatePicker format="YYYY-MM-DD" placeholder="请选择项目截止时间" style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            name="status"
            label="项目状态"
            rules={[{ required: true, message: '请选择项目状态' }]}
          >
            <Select placeholder="请选择项目状态">
              <Option value="待完成">待完成</Option>
              <Option value="进行中">进行中</Option>
              <Option value="已完成">已完成</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      {/* 新增任务模态框 */}
      <Modal
        title="新增任务"
        open={addTaskModalVisible}
        onOk={handleAddTaskOk}
        onCancel={() => {
          setAddTaskModalVisible(false);
          taskForm.resetFields();
        }}
        okText="确定"
        cancelText="取消"
        id="add-task-modal"
      >
        <Form
          form={taskForm}
          layout="vertical"
        >
          <Form.Item
            name="taskName"
            label="任务名称"
            rules={[{ required: true, message: '请输入任务名称' }]}
          >
            <Input placeholder="请输入任务名称" />
          </Form.Item>
          <Form.Item
            name="startTime"
            label="开始时间"
            rules={[{ required: true, message: '请选择开始时间' }]}
          >
            <DatePicker format="YYYY-MM-DD" placeholder="请选择开始时间" style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            name="endTime"
            label="结束时间"
            rules={[{ required: true, message: '请选择结束时间' }]}
          >
            <DatePicker format="YYYY-MM-DD" placeholder="请选择结束时间" style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            name="priority"
            label="优先级"
            rules={[{ required: true, message: '请选择优先级' }]}
          >
            <Select placeholder="请选择优先级">
              <Option value="高">高</Option>
              <Option value="中">中</Option>
              <Option value="低">低</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="taskStatus"
            label="任务状态"
            rules={[{ required: true, message: '请选择任务状态' }]}
          >
            <Select placeholder="请选择任务状态">
              <Option value="未开始">未开始</Option>
              <Option value="进行中">进行中</Option>
              <Option value="已完成">已完成</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="category"
            label="分类标签"
            rules={[{ required: true, message: '请选择分类标签' }]}
          >
            <Select placeholder="请选择分类标签">
              <Option value="开发">开发</Option>
              <Option value="设计">设计</Option>
              <Option value="测试">测试</Option>
              <Option value="文档">文档</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="notes"
            label="备注信息"
          >
            <Input.TextArea placeholder="请输入备注信息" />
          </Form.Item>
        </Form>
      </Modal>

      <style jsx>{`
        .light-row {
          background-color: #eef4f8;
        }
        
        :global(.ant-table-thead > tr > th) {
          background-color: #f5f5f5;
          font-weight: normal;
        }
        
        :global(.ant-table-tbody > tr > td) {
          border-bottom: none;
        }
        
        :global(.ant-table-thead > tr > th) {
          border-bottom: none;
        }
        
        :global(.ant-table-container) {
          border-top: 1px solid #f0f0f0;
          border-left: 1px solid #f0f0f0;
          border-right: 1px solid #f0f0f0;
        }
        
        :global(.ant-table-thead > tr:first-child > th:first-child) {
          border-top-left-radius: 0;
        }
        
        :global(.ant-table-thead > tr:first-child > th:last-child) {
          border-top-right-radius: 0;
        }
        
        :global(.ant-picker-focused .ant-picker-input input),
        :global(.ant-picker-input input:focus) {
          background-color: transparent !important;
          border-color: transparent !important;
          box-shadow: none !important;
          outline: none !important;
        }

        :global(.ant-picker-input input) {
          user-select: none !important;
        }
        
        // 确保选中文本背景透明
        :global(.ant-picker-input input::selection) {
          background: transparent !important;
          color: inherit !important;
        }
        :global(.ant-picker-input input::-moz-selection) {
          background: transparent !important;
          color: inherit !important;
        }
      `}</style>
    </div>
  );
};

export default ProjectPlan;